package com.controller;

import com.entity.User;
import com.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author: foshou.zhang
 * Date : 2016/3/8 0008
 * Time :下午 7:36
 */
@RequestMapping("register")
@Controller
public class RegisterController {
    @Resource
    private IUserService userService;

    /**
     * 进入注册页面
     *
     * @return
     */
    @RequestMapping("toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     * 用户进行注册
     *
     * @param request
     * @return
     */
    @RequestMapping("registering")
    public String register(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setCategory(1);
        System.out.println("password = " + password);
        userService.insertUser(user);
        return "redirect:/login/toLogin.html";
    }

    /**
     * 检查用户名是否被用
     *
     * @param request
     * @param response
     */
    @RequestMapping("checkUsername")
    public void checkUsername(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            if (userService.checkUsername(username)) {
                pw.print("ERROR");
            } else {
                pw.print("SUCCESS");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}
